package com.liuche.framework.biz.context.holder;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.liuche.framework.common.constant.GlobalConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author：liuche
 * @Date：2024年07月07日 16:05
 * @Description：提取请求头中的用户 ID 保存到上下文中，以方便后续使用
 */
@Slf4j
public class UserContextHolder {
    private static final ThreadLocal<Map<String, Object>> USER_CONTEXT_THREAD_LOCAL = TransmittableThreadLocal.withInitial(HashMap::new);

    public static void setVal(String k, Object v) {
        Map<String, Object> map = USER_CONTEXT_THREAD_LOCAL.get();
        map.put(k, v);
    }

    public static Object getVal(String k) {
        return USER_CONTEXT_THREAD_LOCAL.get().get(k);
    }

    public static void remove() {
        USER_CONTEXT_THREAD_LOCAL.remove();
    }

    /**
     * 设置用户 ID
     *
     * @param value
     */
    public static void setUserId(Object value) {
        USER_CONTEXT_THREAD_LOCAL.get().put(GlobalConstants.HEADER_USER_ID, value);
    }

    /**
     * 获取用户 ID
     *
     * @return
     */
    public static Long getUserId() {
        Object value = USER_CONTEXT_THREAD_LOCAL.get().get(GlobalConstants.HEADER_USER_ID);
        if (Objects.isNull(value)) {
            return null;
        }
        return Long.valueOf(value.toString());
    }
}